package com.geek.jdbc.pool.druid;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @Desc TODO
 * @Author
 * @Date 2025/11/17
 *
 * 如何使用Druid数据源连接池？
 * 1.导入druid-1.1.10.jar的jar包 ----> Add as Library
 * 2.创建druid.properties配置文件
 * 3.创建连接池  DruidDataSource pool = (DruidDataSource)DruidDataSourceFactory.createDataSource(Properties properties);
 * 4.API方法
 *   4.1 getConnection() 获取连接
 *   4.2 conn.close()    归还连接，本质上使用DruidPooledConnection，将连接进行归还
 */
public class DruidDemo {

    public static void main(String[] args) {
        //druid.properties存放在项目路径下
        //FileInputStream fis = new FileInputStream("druid.properties");

        //druid.properties存放在与本类同路径下
        InputStream is = DruidDemo.class.getResourceAsStream("druid.properties");
        Properties props = new Properties();

        DruidPooledConnection conn1 = null;
        try {
            //加载Properties配置文件信息
            props.load(is);
            //获取 DruidDataSource 数据源  com.alibaba.druid.pool.DruidDataSource
            DruidDataSource pool = (DruidDataSource)DruidDataSourceFactory.createDataSource(props);
            System.out.println("pool = "+pool.getClass());

            //获取连接对象
            conn1 = pool.getConnection();
            //com.mysql.cj.jdbc.ConnectionImpl@7f77e91b
            System.out.println("conn1 = "+conn1);

            //根据女生ID查询信息
            PreparedStatement ppst = conn1.prepareStatement("select name from girl where id = ?");
            ppst.setInt(1 , 3);
            ResultSet rs = ppst.executeQuery();
            while (rs.next()) {
                System.out.println("3号女生的信息 = "+rs.getString("name"));
            }

            //测试提前归还连接
            if(conn1!=null){
                try {
                    conn1.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

            //再次尝试从连接池中获取连接对象  此时抛出异常信息 com.alibaba.druid.pool.GetConnectionTimeoutException
            //当提前归还连接对象  com.mysql.cj.jdbc.ConnectionImpl@7f77e91b
            DruidPooledConnection conn2 = pool.getConnection();
            System.out.println("conn2 = "+conn2);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //归还资源
            if(conn1!=null){
                try {
                    //DruidPooledConnection 重写close() 将连接归还至连接池中，不做物理层面的真正释放
                    conn1.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

}
